package com.authapi.sample.api.controller;

import com.authapi.sample.api.entity.Menu;
import com.authapi.sample.api.entity.RoleMenu;
import com.authapi.sample.api.entity.User;
import com.authapi.sample.api.entity.UserRole;
import com.authapi.sample.api.model.Request.RoleMenu.UpdateRoleMenuRequest;
import com.authapi.sample.api.model.Request.RoleUser.UpdateRoleUserRequest;
import com.authapi.sample.api.model.Response.Common.Result;
import com.authapi.sample.api.model.Response.Common.ResultList;
import com.authapi.sample.api.service.impl.MenuServiceImpl;
import com.authapi.sample.api.service.impl.RoleMenuServiceImpl;
import lombok.var;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.stereotype.Controller;

import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import java.util.stream.Collectors;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author Baomidou
 * @since 2024-09-26
 */
@RestController
@RequestMapping("/roleMenu")
public class RoleMenuController {

    @Autowired
    private RoleMenuServiceImpl roleMenuService;

    @Autowired
    private MenuServiceImpl menuService;

    //获取角色的菜单列表
    @GetMapping("/getMenuList")
    public ResultList<List<Menu>> getMenuList(String roleId) {
        List<String> menuIds = roleMenuService
                .query().eq("role_id",roleId).list()
                .stream().map(RoleMenu::getMenuId).collect(Collectors.toList());
        if(menuIds.size()>0){
            var menuList = menuService.listByIds(menuIds);

            return ResultList.Success(menuList);
        }
        else{
            return ResultList.Success(new ArrayList<>());
        }

    }

    //更新角色的菜单列表
    @PostMapping("/UpdateRoleMenu")
    public Result< UserRole> UpdateRoleMenu(@RequestBody UpdateRoleMenuRequest request) {
        List<String> Ids = roleMenuService
                .query().eq("role_id",request.roleId).list()
                .stream().map(RoleMenu::getId).collect(Collectors.toList());
        roleMenuService.removeByIds(Ids);
        var _menuIds = request.menuIds;
//        for(int i=0;i<_menuIds.size();i++){
//
//
//            var  parentIds = getAllParentsIds(new ArrayList<>(),_menuIds.get(i));
//            for(int j=0;j<parentIds.size();j++){
//                if(!_menuIds.contains(parentIds.get(j))){
//                    _menuIds.add(parentIds.get(j));
//                }
//            }
//        }
        for(int i=0;i<_menuIds.size();i++){
            int finalI = i;
            UUID uuid = UUID.randomUUID();
            String id = uuid.toString();
            var userRole = new RoleMenu(){
                {
                    setId(id);
                    setMenuId(request.menuIds.get(finalI));
                    setRoleId(request.roleId);
                }
            };
            roleMenuService.save(userRole);
        }


        return Result.Success(null);
    }



}
